package com.adream.cliniq.server.system;

import java.sql.SQLException;

import org.apache.commons.dbcp.BasicDataSource;

/**
 * This class extends the DBCP datasource in order to handle
 * the embedded derby database deviations, especially the database shutdown. 
 * @author apuranik
 */
public class DerbyDataStore extends BasicDataSource {

	public synchronized void close() throws SQLException {
		super.close();
		if (chekIfEmbeddedDerby()) {
			shutdownDerby();
		}
	}

	/**
	 * Checks if underlying database is Derby.
	 * 
	 * @param a_connectionUrl
	 * @return
	 */
	private boolean chekIfEmbeddedDerby() {
		String embeddedDerbyDriver= "org.apache.derby.jdbc.EmbeddedDriver";
		String dbDriver = getDriverClassName();
		return (embeddedDerbyDriver.equals(dbDriver));
	}

	/**
	 * Shuts down Derby.
	 *  
	 * @param a_connectionUrl
	 * @throws SQLException
	 */
	private void shutdownDerby() throws SQLException {
		// We use the existing url to append the shutdown syntax.
		String connectionUrl = getUrl();
		String shutdownUrl = connectionUrl.replaceFirst("create=true", "shutdown=true");

		// We set the new url and get a connection in order to shutdown the database.
		setUrl(shutdownUrl);
		boolean gotSqlEx = false;
		try {
			createDataSource().getConnection();
		} catch (SQLException se) {
			gotSqlEx = true;
		}

		if (!gotSqlEx) {
			throw new SQLException("Could not shutdown the embedded database.");
		}
	}
}
